﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace VietNamKey
{
    [DefaultEvent("SettingChanged")]
    public partial class ucShorthand : UserControl
    {
        public event EventHandler SettingChanged;
        bool isOk = false;
        public ucShorthand()
        {
            InitializeComponent();
            if(LicenseManager.UsageMode != LicenseUsageMode.Designtime)
                Reload();
        }

        public void Reload()
        {
            isOk = false;
            lvList.Items.Clear();
            foreach (var item in Global.KeySettings.ShorthandList)
            {
                lvList.Items.Add(new ListViewItem(item));
            }
            isOk = true;
        }
        private void RaiseEvent()
        {
            Global.KeySettings.ShorthandList.Clear();
            foreach (ListViewItem item in lvList.Items)
            {
                Global.KeySettings.ShorthandList.Add(new[] { item.SubItems[0].Text, item.SubItems[1].Text });
            }
            if (SettingChanged != null) SettingChanged(this, new EventArgs());
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            lvList.Items.Add(new ListViewItem(new[] { txtReplace.Text, txtContent.Text }));
            RaiseEvent();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            lvList.Items[lvList.SelectedIndices[0]] = new ListViewItem(new[] { txtReplace.Text, txtContent.Text });
            RaiseEvent();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            lvList.Items.RemoveAt(lvList.SelectedIndices[0]);
            RaiseEvent();
        }

        private void lvList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isOk) return;
            if (lvList.SelectedIndices.Count!=0)
            {
                btnEdit.Enabled = btnDelete.Enabled = true;

                txtReplace.Text = lvList.Items[lvList.SelectedIndices[0]].SubItems[0].Text;
                txtContent.Text = lvList.Items[lvList.SelectedIndices[0]].SubItems[1].Text;
            }
            else
                btnEdit.Enabled = btnDelete.Enabled = false;
        }
    }
}
